const setCookieParser = require("set-cookie-parser")
const axios = require("axios").default;
const rs = require("randomstring");
const qs = require("querystring");
const util = require("util");
const Toolbox = require("../Toolbox");
const ComAxerrRes = require("../CommonAxerrHandler")

class SimpleInyota {
  constructor() {

  }

  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{cookie_str:String}}>}
   */
  login() {
    let username = "teng", password = "985211";
    return new Promise(resolve => {
      axios.post('https://app.hiaita.com/mag/user/v1/user/login',qs.stringify({
        account: username,
        password: password
      }), {
          headers: {
            "User-Agent": "okhttp/3.8.1"
          }
        }
      ).then(axresp => {
        if (axresp.data && axresp.status == 200 && axresp.data.success === true && axresp.data.data && axresp.data.data.user_id && axresp.headers["set-cookie"]) {
          /**@type {string[]} */
          let setCookies = axresp.headers["set-cookie"];
          let parsed_cookies = setCookies.map(e => setCookieParser.parse(e));
          let c_str = parsed_cookies.map(e => {
            return e.map(s => `${s.name}=${s.value}`).join("; ")
          }).join("; ");
          resolve({
            ok: true,
            msg: "ok",
            data: {
              cookie_str: c_str
            }
          })
        } else {
          throw new Error(`不符合预期的http返回,data=[${util.inspect(
            axresp.data
          )}],headers=[${util.inspect(axresp.headers)}]`)
        }
      }).catch(axerr => {
        ComAxerrRes(resolve)(axerr);
      })
    })
  }
};

let inyota = new SimpleInyota;
let p_login = inyota.login();


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{uptoken:String}}>}
 */
function get_token() {
  return new Promise(async resolve => {
    let o_login = await p_login;
    if (!o_login.ok) {
      return ComAxerrRes(resolve)(`failed to login:${o_login.msg}`)
    }
    axios.get(`https://app.hiaita.com/core/attachment/attachment/getQiNiuToken`, {
      headers: {
        cookie: o_login.data.cookie_str
      }
    }).then(axresp => {
      if (axresp.data && axresp.data.success === true && axresp.data.data) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            uptoken: axresp.data.data
          }
        })
      } else {
        throw new Error(`not sanity resp:HTTP ${axresp.status}:data = ${axresp.data}`)
      }
    }).catch(axerr => {
      ComAxerrRes(resolve)(axerr);
    })
  })
}


module.exports = {
  get_token: get_token
}